import {Component, OnInit, ViewChild} from '@angular/core';
import {ModalDirective} from 'ngx-bootstrap';
import {HttpService} from '../../../lib/service/http.service';
import {LocalStorageService} from '../../../lib/service/local-storage.service';
import {OrderConsignment, EditExpresFee, EditGoodsFee} from './order-manage';
import {adSystemApiUrl, AliyunOssOutputUrl} from 'config/api';
import {OrderService} from './order.service';

@Component({
  selector: 'app-order-manage',
  templateUrl: './order-manage.component.html',
  styleUrls: ['./order-manage.component.scss'],
  providers: [LocalStorageService, OrderService]
})

export class OrderManageComponent implements OnInit {

  type: string;
  message: string;
  isShow = false;

  totalItems: number;
  itemsPerPage = 10;
  currentPage = 1;

  applet_uuid;
  orderList = [];
  orderTab = 'all';

  order_no = '';
  nickName = '';
  goods_name = '';
  order_time = '';
  order_type = '0';
  order_status = '0';


  deliveryList = [];
  recipients: string;  // 收件人
  tel: number;  // 联系电话
  address: string;  // 收货地址
  editType = 'express';
  orderGoodsList = [];
  forbidden = false;
  deliveryInfoList = [];  // 物流信息
  expressName: string;
  expressNo: number;
  loadingShow = true;
  customDate = false;
  checkedIds = [];

  aliyunOssOutputUrl = AliyunOssOutputUrl;
  orderConsignment = new OrderConsignment;
  editExpresFee = new EditExpresFee;
  editGoodsFee = new EditGoodsFee;

  tradeInfo;
  refund;

  private selDate = 'MM/DD/YYYY';
  private minDate = '';
  private maxDate = '';
  private startDate = '';
  private endDate = '';
  private disableDays: Array<number> = [];    // For Sunday and Saturday
  private toContainPrevMonth = false;
  private toContainNextMonth = false;

  @ViewChild('editModal') public editModal: ModalDirective;
  @ViewChild('deliverModal') public deliverModal: ModalDirective;
  @ViewChild('viewModal') public viewModal: ModalDirective;
  @ViewChild('editFeeModal') public editFeeModal: ModalDirective;
  @ViewChild('refoundModal') public refoundModal: ModalDirective;
  @ViewChild('tradeModal') public tradeModal: ModalDirective;

  constructor(private localStorageService: LocalStorageService,
              private httpService: HttpService,
              private orderService: OrderService) {
  }

  ngOnInit() {
    this.applet_uuid = this.localStorageService.getNowApplet().applet_uuid;
    // this.getOrderList(1, '', this.nickName, this.goods_name, this.order_no, this.start_date, this.end_date);
    this.getOrderList_v2();
  }

  changeOrderTime(params = '') {
    this.startDate = '';
    this.endDate = '';
    this.order_time = params;
    this.customDate = false;
    this.checkedIds = [];
    this.currentPage = 1;
    this.getOrderList_v2();
  }

  customOrderTime() {
    this.order_time = '';
    this.customDate = true;
  }

  changeOrderType(params = '') {
    this.startDate = '';
    this.endDate = '';
    this.currentPage = 1;
    this.order_type = params;
    this.checkedIds = [];
    this.getOrderList_v2();
  }

  changeOrderStatus(params = '') {
    this.startDate = '';
    this.endDate = '';
    this.order_status = params;
    this.currentPage = 1;
    this.checkedIds = [];
    this.getOrderList_v2();
  }

  // 更改订单勾选状态
  changeOrderChecked(data) {
    if (data.isChecked) {
      this.checkedIds.every((val, idx, array) => {
        if (val === data.id) {
          this.checkedIds.splice(idx, 1);
          return false;
        }
        return true;
      });
    } else {
      this.checkedIds.push(data.id);
    }
    data.isChecked = !data.isChecked;
  }

  getOrderList_v2() {
    this.loadingShow = true;
    this.orderService.getOrderList(
      this.order_no,
      this.nickName,
      this.goods_name,
      this.order_time,
      this.order_type,
      this.order_status,
      this.startDate,
      this.endDate,
      this.currentPage,
      this.itemsPerPage
    ).subscribe(res => {
      this.totalItems = res.data.total;
      this.orderList = res.data.data;
      setTimeout(
        () => {
          this.loadingShow = false;
        }
        , 500);
      this.orderList.every((val, idx, array) => {

        switch (val.pay_status) {
          case 1: // 未支付
            val.pay_status_remark = '待付款';
            break;
          case 4: // 已支付
            if (val.express_status === 1) {
              if (!!val.activity_goods_shopping_order) {
                if (val.activity_goods_shopping_order.activity_goods_shopping.status === '已完成') {
                  val.pay_status_remark = '待发货';
                }
              } else {
                val.pay_status_remark = '待发货';
              }
            } else if (val.express_status === 2) {
              val.pay_status_remark = '待收货';
            } else if (val.express_status === 4) {
              val.pay_status_remark = '交易成功';
            }
            break;
          case 3: // 支付中
            val.pay_status_remark = '支付中';
            break;
          /*case 6: // 已作废
            val.pay_status_remark = '关闭交易';
            break;*/
        }
        if (val.order_state === 3) {
          val.pay_status_remark = '关闭交易';
        }
        if (!!val.activity_goods_shopping_order) {
          const shopping = val.activity_goods_shopping_order.activity_goods_shopping;
          if (shopping.status === '已完成') {
            if (shopping.activity_open_prize_status === 0) {
              val.group_status = '待开奖';
              val.status = '待开奖';
            } else if (shopping.activity_open_prize_status === 1) {
              if (val.activity_goods_lottery.is_win === 0) {
                val.group_status = '未中奖';
              } else {
                switch (val.activity_goods_lottery.activity_goods_level) {
                  case 1:
                    val.group_status = '一等奖';
                    break;
                  case 2:
                    val.group_status = '二等奖';
                    break;
                  case 3:
                    val.group_status = '三等奖';
                    break;
                  case 4:
                    val.group_status = '四等奖';
                    break;
                  case 5:
                    val.group_status = '五等奖';
                    break;
                  case 5:
                    val.group_status = '六等奖';
                    break;
                }
              }
            }
          }
        }

        let calculateFee = 0;
        let flag = 0;
        let flag1 = 0;
        val.order_sub.every((val1, idx1, array1) => {
          calculateFee += val1.fee * val1.quantity;
          // 如果不存在退款
          if (!val1.order_refund || val.express_status !== 1 || val1.order_refund.refund_status === 3) {
            flag = 1;
          }
          if (!val1.order_refund || val1.order_refund.refund_status !== 5) {
            flag1 = 1;
          }
          return true;
        });
        if (flag === 0) {
          val.pay_status_remark = '';
          // val.pay_status_remark = '';
        } else if (flag === 1) {
          // val.pay_status_remark = 'mdzz';
        }

        if (flag === 0 && flag1 !== 1) {
          val.pay_status_remark = '关闭交易';
        }

        val.fee = calculateFee + val.express_fee;

        // 判断是否选中
        if (!!this.checkedIds.length) {
          this.checkedIds.every((val1, idx1, array1) => {
            if (val1 === val.id) {
              val.isChecked = true;
              return false;
            }
            val.isChecked = false;
            return true;
          });
        } else {
          val.isChecked = false;
        }
        return true;
      });
    });
  }

  // 按搜索结果导出
  exportSearch() {
    const link = document.createElement('a');
    this.orderService.down_xsl(
      this.order_no,
      this.nickName,
      this.goods_name,
      this.order_time,
      this.order_type,
      this.order_status,
      this.startDate,
      this.endDate,
      1,
      1000
    ).subscribe(data => {
      console.log(data);
      link.setAttribute('href', window.URL.createObjectURL(data));
      const today = new Date();
      const now = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate() + ' ' + today.getHours() + ':' + today.getMinutes() + ':' + today.getSeconds();
      console.log(now);
      link.setAttribute('download', '订单' + now + '.xls');
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    });
  }

  // 按勾选结果导出
  exportChecked() {
    if (!this.checkedIds.length) {
      this.type = 'success';
      this.message = '请选择需要导出的订单';
      this.isShow = true;
      return;
    }
    var link = document.createElement('a');
    this.orderService.down_xsl_checked(
      JSON.stringify(this.checkedIds)
    ).subscribe( data => {
      link.setAttribute('href', window.URL.createObjectURL(data));
      const today = new Date();
      const now = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate() + ' ' + today.getHours() + ':' + today.getMinutes() + ':' + today.getSeconds();
      console.log(now);
      link.setAttribute('download', '订单' + now + '.xls');
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    });
  }

  // 改变订单状态
  /*changeOrderStatus(status?: string) {
    this.orderTab = status || 'all';
    this.getOrderList(1, this.orderTab, this.nickName, this.goods_name, this.order_no, this.start_date, this.end_date);
  }

  // 选择订单时间
  changeOrderTime(range: number){
    this.order_time = range;
    let todayDate = new Date();
    this.end_date = todayDate.getFullYear()+'-'+(todayDate.getMonth()+1)+'-'+todayDate.getDate()+' 23:59:59';
    if(!!range){
      let myDate = new Date(),
        stamp = myDate.setDate(myDate.getDate()-range),
        date = new Date(stamp);
      this.start_date = date.getFullYear()+'-'+(date.getMonth()+1)+'-'+date.getDate()+' 00:00:00';
      this.getOrderList(1,this.orderTab,this.nickName,this.goods_name,this.order_no,this.start_date,this.end_date);
    }else{
      this.start_date = '';
      this.getOrderList(1,this.orderTab,this.nickName,this.goods_name,this.order_no,this.start_date,this.end_date);
    }
  }

  // 搜索
  search() {
    this.getOrderList(1, this.orderTab, this.nickName, this.goods_name, this.order_no, this.start_date, this.end_date);
  }*/

  /*reset() {
    this.nickName = '';
    this.goods_name = '';
    this.order_no = null;
    this.getOrderList(1, this.orderTab, this.nickName, this.goods_name, this.order_no, this.start_date, this.end_date);
  }*/

  search() {
    this.currentPage = 1;
    this.getOrderList_v2();
  }

  reset() {
    this.checkedIds = [];
    this.currentPage = 1;
    this.nickName = '';
    this.goods_name = '';
    this.order_no = '';
    // this.order_time = '';
    // this.order_type = '0';
    // this.order_status = '0';
    this.getOrderList_v2();
  }

  // 获取快递公司列表
  getDeliveryList() {
    const url = `${adSystemApiUrl}/v1/member/express/list?page=1&pageSize=999`;
    return this.httpService.httpGetAuth(url).subscribe(
      res => {
        this.deliveryList = res.data.data;
      }
    );
  }

  // 发货弹窗
  deliverDialog(data: any) {
    this.recipients = '';
    this.tel = null;
    this.address = '';
    this.orderConsignment.express_id = 0;
    this.orderConsignment.express_no = '';
    this.getDeliveryList();
    this.orderConsignment.applet_uuid = this.applet_uuid;
    this.orderConsignment.order_no = data.order_no;
    this.orderConsignment.remark = data.remark;
    if (data.applet_member_address) {
      const address = this.turnParse(data.applet_member_address);
      if (address.name) {
        this.recipients = address.name;
      }
      this.tel = address.mobile;
      this.address = address.province + address.city + address.district + address.detail;

    }
    this.deliverModal.show();
  }

  submitOrder() {
    const url = `${adSystemApiUrl}/v1/member/order/consignment`;
    return this.httpService.httpPostAuth(url, this.orderConsignment).subscribe(
      res => {
        if (res.code === 2000) {
          this.type = 'success';
          this.message = '发货成功';
          this.isShow = true;
          this.deliverModal.hide();
          this.orderConsignment.express_no = '';
          this.orderConsignment.express_id = 0;
          this.getOrderList_v2();
          // this.getOrderList(1, this.orderTab, this.nickName, this.goods_name, this.order_no, this.start_date, this.end_date);
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }

  // 查看物流信息
  deliveryInfo(data: any) {
    const url = `${adSystemApiUrl}/v1/member/logistics/get_order_v2` +
      `?applet_uuid=${this.applet_uuid}&order_no=${data.order_no}&applet_member_id=${data.applet_member_id}`;
    return this.httpService.httpGetAuth(url).subscribe(
      res => {
        console.log(res);
        if (res.code === 2000) {
          this.deliveryInfoList = res.data.express;
          // this.deliveryInfoList.reverse();
          this.expressNo = res.data.order_no;
          this.expressName = res.data.express_name;
          this.viewModal.show();
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );

  }

  turnParse(str) {
    return JSON.parse(str);
  }

  // 改价
  editFeeDlg(data: any) {
    this.editExpresFee.order_no = data.order_no;
    this.editExpresFee.express_fee = data.express_fee / 1000;
    this.editGoodsFee.order_no = data.order_no;
    this.orderGoodsList = data.order_sub;
    if (!this.editExpresFee.express_fee) {
      this.editType = 'goods';
    }
    this.editFeeModal.show();
  }

  //
  tradeDlg(data: any) {
    this.tradeInfo = null;
    this.orderService.getOrderInfo(data.order_no).subscribe(res => {
      this.tradeInfo = res.data;
      // this.tradeInfo.express_info.reverse();
      this.tradeInfo.applet_member_address = JSON.parse(this.tradeInfo.applet_member_address);
    });
    this.tradeModal.show();
  }

  // 退款
  refoundDlg(data: any) {

    this.refund = null;
    this.orderService.getRefundReason().subscribe(rs => {
      // console.log(rs);
      this.orderService.getRefundOrder(data.id).subscribe(res => {
        // console.log(res);
        this.refund = res.data;
        this.refund.refund_reason_remark = '';
        /*this.refund.every((val, idx, array) => {
          console.log(val);
        });*/

        for (const v in rs.data) {
          if (parseInt(v, 10) === this.refund.refund_reason) {
            this.refund.refund_reason_remark = rs.data[v];
          }
        }
      });
    });
    /*this.editExpresFee.order_no = data.order_no;
    this.editExpresFee.express_fee = data.express_fee / 1000;
    this.editGoodsFee.order_no = data.order_no;
    this.orderGoodsList = data.order_sub;
    if (!this.editExpresFee.express_fee) {
      this.editType = 'goods';
    }*/
    this.refoundModal.show();
  }

  confirmRefund() {
    this.orderService.confirmRefund(this.refund.order_sub_id).subscribe(res => {
      alert(res.message);
      this.refoundModal.hide();
      this.getOrderList_v2();
    });
  }

  refuseRefund() {
    this.orderService.refuseRefund(this.refund.order_sub_id).subscribe(res => {
      alert(res.message);
      this.refoundModal.hide();
      this.getOrderList_v2();
    });
  }

  // 选中需改价商品
  checkedEditGoods() {
    if (!this.editGoodsFee.order_sub_id) {
      return;
    }
    this.orderGoodsList.every((val, idx, array) => {
      if (val.id === this.editGoodsFee.order_sub_id) {
        this.editGoodsFee.fee = val.fee / 1000;
        return false;
      }
    });
  }

  // 提交改价运费
  editExpressSubmit() {
    this.forbidden = true;
    this.editExpresFee.applet_uuid = this.applet_uuid;
    const url = `${adSystemApiUrl}/v1/member/order/edit_express_fee`;
    return this.httpService.httpPostAuth(url, this.editExpresFee).subscribe(
      res => {
        this.forbidden = false;
        if (res.code === 2000) {
          this.type = 'success';
          this.message = '修改成功';
          this.isShow = true;
          this.getOrderList_v2();
          // this.getOrderList(1, this.orderTab, this.nickName, this.goods_name, this.order_no, this.start_date, this.end_date);
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }

  // 提交改价商品
  editGoodsSubmit() {
    if (!this.editGoodsFee.order_sub_id) {
      this.type = 'info';
      this.message = '请选择需改价的商品';
      this.isShow = true;
      return;
    }
    this.forbidden = true;
    this.editGoodsFee.applet_uuid = this.applet_uuid;
    this.editGoodsFee.fee = +(this.editGoodsFee.fee * 100).toFixed(0) / 100;
    const url = `${adSystemApiUrl}/v1/member/order/edit_goods_fee`;
    return this.httpService.httpPostAuth(url, this.editGoodsFee).subscribe(
      res => {
        this.forbidden = false;
        if (res.code === 2000) {
          this.type = 'success';
          this.message = '修改成功';
          this.isShow = true;
          this.getOrderList_v2();
          // this.getOrderList(1, this.orderTab, this.nickName, this.goods_name, this.order_no, this.start_date, this.end_date);
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }

  /*pageChanged(event: any) {
    this.getOrderList(event.page, this.orderTab, this.nickName, this.goods_name, this.order_no, this.start_date, this.end_date);
  }*/

  pageChanged(event: any) {
    this.currentPage = event.page;
    this.getOrderList_v2();
    // this.pageChanged();
    window.scrollTo(0, 0);
  }

  setDate(date) {
    this.selDate = date;
  }

  checkStartDate(date) {
    this.startDate = date;
    this.currentPage = 1;
    this.getOrderList_v2();
  }

  checkEndDate(date) {
    this.endDate = date;
    this.currentPage = 1;
    this.getOrderList_v2();
  }

}
